import threading

from flask import request, redirect, session

from utils.sql_info import get_user_id
from utils.sql_user import get_user_lnh, get_user_cookie


lock = threading.Lock()


def check_user_state(func):
    """
    检测用户登录状态
    :param func:
    :return:
    """
    def check_user(*args):
        email = request.cookies.get('email')
        up = request.cookies.get('up')

        # 取消able认证
        # if session.get('able'):
        #     result = func(*args)
        #     return result

        if email is None or up is None:
            return redirect("/user/login")

        with lock:
            cookie = get_user_cookie(email)

        if cookie is None or cookie == '':
            return redirect("/user/login")

        # # 新增cookie认证
        # if cookie == up:
        #     result = func(*args)
        #     return result

        if not up == cookie:
            return redirect("/user/login")

        if 'email' not in session.keys() or\
                'level' not in session.keys() or\
                'uid' not in session.keys():

            session['email'] = email

            with lock:
                session['level'], session['name'], session['head'] = get_user_lnh(email)
                session['uid'] = get_user_id(email)

            session['cookie'] = cookie
            session.permanent = True

        result = func(*args)
        return result
    return check_user

